package com.woniuxy.joylifeforum.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.common.entity.*;
import com.woniuxy.common.mapper.*;
import com.woniuxy.joylifeforum.service.CommunityService;
import com.woniuxy.joylifeforum.utils.AliyunOSSUtil;
import com.woniuxy.joylifeforum.utils.ForumRedis;
import com.woniuxy.joylifeforum.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 用于社区相关服务
 */
@Service
public class CommunityServiceImpl implements CommunityService {
    @Autowired
    private ForumTopicMapper forumTopicMapper;
    @Autowired
    private ForumReplyMapper forumReplyMapper;
    @Autowired
    private CenterUserMapper centerUserMapper;
    @Autowired
    private ForumForumMapper frumForumMapper;
    @Autowired
    private ForumConcernMapper forumConcernMapper;
    @Autowired
    private ForumTopicPraiseMapper forumTopicPraiseMapper;
    @Autowired
    private ForumRedis forumRedis;
    @Autowired
    private ForumPhotoMapper forumPhotoMapper;
    @Autowired
    private ForumExpMapper forumExpMapper;
    @Autowired
    private ForumAdminMapper forumAdminMapper;
    @Autowired
    private ForumAdminApplyMapper forumAdminApplyMapper;
    @Autowired
    private RedisUtil redisUtil;

    /*
    用户关注的社区
     */
    @Override
    public List<Map<String, Object>> findMyConcern(String userId) {
        //查询我的关注
        ForumConcernExample concernExample = new ForumConcernExample();
        concernExample.createCriteria().andUserIdEqualTo(userId);
        List<ForumConcern> forumConcerns = forumConcernMapper.selectByExample(concernExample);
        //获取关注社区id，便于检索
        List<String> forumStr = new ArrayList<>();
        forumStr.add("");
        for (ForumConcern forumConcern : forumConcerns) {
            forumStr.add(forumConcern.getForumId());
        }
        //关注的社区
        ForumForumExample forumExample = new ForumForumExample();
        forumExample.createCriteria().andIdIn(forumStr);
        List<ForumForum> forumForums = frumForumMapper.selectByExample(forumExample);

        //检索经验值
        List<Map<String, Object>> data = new ArrayList<>();
        for (ForumForum forumForum : forumForums) {
            ForumExpExample expExample = new ForumExpExample();
            ForumExpExample.Criteria criteria = expExample.createCriteria();
            criteria.andForumIdEqualTo(forumForum.getId());
            criteria.andUserIdEqualTo(userId);
            Integer exp = forumExpMapper.selectByExample(expExample).get(0).getExp();
            Map<String, Object> map = new HashMap<>();
            map.put("forum", forumForum);
            map.put("exp", exp);
            data.add(map);
        }
        Collections.sort(data, (o1, o2) -> Integer.parseInt(o2.get("exp").toString()) - Integer.parseInt(o1.get("exp").toString()));
        return data;
    }

    /*
    热门社区
     */
    @Override
    public List<Map<String, Object>> findActiveConcern(String userId) {
        //查询关注量最高的10个社区
        List<Map<String, Object>> data = new ArrayList<>();
        List<String> stringIntegerMap = forumConcernMapper.selectByActive(10);
        for (String forumId : stringIntegerMap) {
            //社区关注量
            long l = forumRedis.findForumUserNum(forumId);
            //社区对象
            ForumForum forumForum = frumForumMapper.selectByPrimaryKey(forumId);
            Map<String, Object> map = new HashMap<>();
            //社区话题量
            long forumTopics = forumRedis.findForumTopicNum(forumId);
            //用户是否关注
            ForumConcernExample concernExample1 = new ForumConcernExample();
            ForumConcernExample.Criteria criteria = concernExample1.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andForumIdEqualTo(forumId);
            List<ForumConcern> forumConcerns = forumConcernMapper.selectByExample(concernExample1);
            if (forumConcerns.size() == 0) {
                map.put("userConcern", 0);
            } else {
                map.put("userConcern", 1);
            }
            map.put("forum", forumForum);
            map.put("concernNum", l);
            map.put("topicsNum", forumTopics);
            data.add(map);
        }
        return data;
    }

    /*
    用户关注社区
     */
    @Override
    public Integer addConcern(String userId, String forumId) {
        //用户是否关注
        ForumConcernExample concernExample1 = new ForumConcernExample();
        ForumConcernExample.Criteria criteria = concernExample1.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andForumIdEqualTo(forumId);
        List<ForumConcern> forumConcerns = forumConcernMapper.selectByExample(concernExample1);
        if (forumConcerns.size() == 0) {
            //用户未关注
            ForumConcern concern = new ForumConcern(UUID.randomUUID().toString(), userId, forumId);
            forumConcernMapper.insert(concern);
            Integer forumNum = Integer.parseInt(redisUtil.get("forumNum" + forumId).toString());
            redisUtil.set("forumNum"+forumId,(forumNum+1));
        }
        //用户已关注
        //用户是否已有经验
        ForumExpExample expExample = new ForumExpExample();
        ForumExpExample.Criteria criteria1 = expExample.createCriteria();
        criteria1.andUserIdEqualTo(userId);
        criteria1.andForumIdEqualTo(forumId);
        List<ForumExp> forumExps = forumExpMapper.selectByExample(expExample);
        if (forumExps.size() == 0) {
            //用户未有经验
            ForumConcern concern = new ForumConcern(UUID.randomUUID().toString(), userId, forumId);
            ForumExp exp = new ForumExp(UUID.randomUUID().toString(), userId, 1, forumId);
            forumExpMapper.insert(exp);
        }
        return 1;
    }

    /*
    用户取消关注
     */
    @Override
    public Integer cancelConcern(String userId, String forumId) {
        //直接删除
        ForumConcernExample concernExample = new ForumConcernExample();
        ForumConcernExample.Criteria criteria = concernExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andForumIdEqualTo(forumId);
        forumConcernMapper.deleteByExample(concernExample);
        Integer forumNum = Integer.parseInt(redisUtil.get("forumNum" + forumId).toString());
        redisUtil.set("forumNum"+forumId,(forumNum-1));
        return 0;
    }

    /*
    查找社区
     */
    @Override
    public List<Map<String, Object>> findForum(String find, String userId) {
        //查找社区
        ForumForumExample forumExample = new ForumForumExample();
        forumExample.createCriteria().andNameLike("%" + find + "%");
        List<ForumForum> forumForums = frumForumMapper.selectByExample(forumExample);
        List<Map<String, Object>> data = new ArrayList<>();
        //遍历赋值
        for (ForumForum forumForum : forumForums) {
            //该社区关注量
            ForumConcernExample concernExample1 = new ForumConcernExample();
            concernExample1.createCriteria().andForumIdEqualTo(forumForum.getId());
            long l = forumConcernMapper.countByExample(concernExample1);
            //该社区话题量
            ForumTopicExample topicExample = new ForumTopicExample();
            topicExample.createCriteria().andForumIdEqualTo(forumForum.getId());
            long forumTopics = forumTopicMapper.countByExample(topicExample);
            //判断是否已关注该社区
            Map<String, Object> map = new HashMap<>();
            ForumConcernExample concernExample = new ForumConcernExample();
            ForumConcernExample.Criteria criteria = concernExample.createCriteria();
            criteria.andForumIdEqualTo(forumForum.getId());
            criteria.andUserIdEqualTo(userId);
            List<ForumConcern> forumConcerns = forumConcernMapper.selectByExample(concernExample);
            if (forumConcerns.size() == 1) {
                //已关注
                map.put("status", 1);
            } else {
                //未关注
                map.put("status", 0);
            }
            map.put("concernNum", l);
            map.put("topicsNum", forumTopics);
            map.put("forum", forumForum);
            data.add(map);
        }
        return data;
    }

    /*
    获取社区简介，单个社区页面使用
     */
    @Override
    public Map<String, Object> findSynopsis(String forumId, String userId) {
        Map<String, Object> map = new HashMap<>();
        //查找社区
        ForumForum forumForum = frumForumMapper.selectByPrimaryKey(forumId);
        map.put("forum", forumForum);
        //判断是否是管理员
        ForumAdminExample forumAdmin = new ForumAdminExample();
        ForumAdminExample.Criteria criteria1 = forumAdmin.createCriteria();
        criteria1.andForumIdEqualTo(forumId);
        criteria1.andUserIdEqualTo(userId);
        List<ForumAdmin> forumAdmins = forumAdminMapper.selectByExample(forumAdmin);
        if (forumAdmins.size() == 1) {
            //是
            map.put("admin", 1);
        } else {
            //不是
            map.put("admin", 0);
        }
        //判断是否关注
        ForumConcernExample concernExample = new ForumConcernExample();
        ForumConcernExample.Criteria criteria = concernExample.createCriteria();
        criteria.andForumIdEqualTo(forumId);
        criteria.andUserIdEqualTo(userId);
        List<ForumConcern> forumConcerns = forumConcernMapper.selectByExample(concernExample);
        if (forumConcerns.size() == 1) {
            //已关注
            map.put("status", 1);
            //查找经验
            ForumExpExample expExample = new ForumExpExample();
            ForumExpExample.Criteria criteria12 = expExample.createCriteria();
            criteria12.andUserIdEqualTo(userId);
            criteria12.andForumIdEqualTo(forumId);
            Integer exp = forumExpMapper.selectByExample(expExample).get(0).getExp();
            map.put("exp", exp);
        } else {
            //未关注
            map.put("status", 0);
            //社区关注量
            long concernl = forumRedis.findForumUserNum(forumId);
            map.put("concernNum", concernl);
            //社区话题量
            long forumTopics = forumRedis.findForumTopicNum(forumId);
            map.put("topicsNum", forumTopics);
        }
        return map;
    }

    /*
    获取社区经验
     */
    @Override
    public Integer findExp(String userId, String forumId) {
        ForumExpExample expExample = new ForumExpExample();
        ForumExpExample.Criteria criteria12 = expExample.createCriteria();
        criteria12.andUserIdEqualTo(userId);
        criteria12.andForumIdEqualTo(forumId);
        Integer exp = forumExpMapper.selectByExample(expExample).get(0).getExp();
        return exp;
    }

    /*
    社区最新动态
     */
    @Override
    public PageInfo<Map<String, Object>> findNewMes(String userId,Integer page, Integer limit, String forumId, String find, Integer site) {
        //检索动态
        //分页
        PageHelper.startPage(page, limit);
        List<ForumTopic> forumTopics = new ArrayList<>();
        if (site == 1) {
            //最新消息
            forumTopics = forumTopicMapper.findLikeNew(forumId, find);
        } else if (site == 2) {
            //最热消息
            forumTopics = forumTopicMapper.findLikeHot(forumId, find);
        } else {
            //最多收藏
            forumTopics = forumTopicMapper.findLikeCollect(forumId, find);
        }
        //遍历赋值
        List<Map<String, Object>> data = new ArrayList<>();
        for (ForumTopic forumTopic : forumTopics) {
            Map<String, Object> map = new HashMap<>();
            CenterUser centerUser = centerUserMapper.selectByPrimaryKey(forumTopic.getUserId());
            //话题点赞数量
            long topicPraiseNum = forumRedis.findTopicPraiseNum(forumTopic.getId());
            //判断本用户是否已点赞
            ForumTopicPraiseExample topicPraise=new ForumTopicPraiseExample();
            ForumTopicPraiseExample.Criteria criteria3 = topicPraise.createCriteria();
            criteria3.andTopicIdEqualTo(forumTopic.getId());
            criteria3.andUserIdEqualTo(userId);
            int praiseStatus = forumTopicPraiseMapper.selectByExample(topicPraise).size();
            //话题评论数量
            long replyNum = forumRedis.findReplyNum(forumTopic.getId());
            //话题照片
            ForumPhotoExample photoExample = new ForumPhotoExample();
            ForumPhotoExample.Criteria criteria1 = photoExample.createCriteria();
            criteria1.andTopicIdEqualTo(forumTopic.getId());
            criteria1.andReplyIdIsNull();
            List<ForumPhoto> forumPhotos = forumPhotoMapper.selectByExample(photoExample);
            //保存
            map.put("forumPhotos", forumPhotos);
            map.put("centerUser", centerUser);
            map.put("forumTopic", forumTopic);
            map.put("topicPraiseNum", topicPraiseNum);
            map.put("praiseStatus", praiseStatus);
            map.put("replyNum", replyNum);
            data.add(map);
        }
        PageInfo<Map<String, Object>> forumTopicsPH = new PageInfo<>(data);
        return forumTopicsPH;
    }
    /*
    上传照片
     */
    @Override
    public String addImgService(MultipartFile img) {
//        String fileName ="";
//        try {
//            //映射路径
//            String path = "D:/img/joylife/";
//
//            File temp = new File("D:/img/joylife");
//            if(!temp.exists()){
//                temp.mkdirs();
//            }
//            //文件名
//            String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");
//            fileName = uuid + img.getOriginalFilename();
//
//            //上传阿里云储存
//            // Endpoint以杭州为例，其它Region请按实际情况填写。
//            String endpoint = "oss-cn-chengdu.aliyuncs.com";
//            // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建。
//            String accessKeyId = "LTAI4G5PQFzXUgWJQTWPPKbd";
//            String accessKeySecret = "XzcI2feaiXVigNwDlOMmMr4OReUORO";
//
//            // 创建OSSClient实例。
//            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//
//            // 上传文件流。
//            /*InputStream inputStream = new FileInputStream(path+fileName);*/
//            InputStream inputStream = img.getInputStream();
//            ossClient.putObject("joylife-hello", fileName, inputStream);
//
//            // 关闭OSSClient。
//            ossClient.shutdown();
//            //System.out.println("上传成功。。。");
//
//
//            //创建文件
//            File file = new File(path, fileName);
//            //保存
//            img.transferTo(file);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        AliyunOSSUtil aliyunOSSUtil = new AliyunOSSUtil();
        String fileUri = null;
        try {
            fileUri = aliyunOSSUtil.uploadFile(img.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
       // System.out.println("url-"+fileUri);
        return fileUri;
    }
    /*
    用户发送话题
     */
    @Override
    @Transactional
    public String addTopicService(String[] imgs, String content, String forumId, String userId) {
        try {
            //插入话题构造表数据
            String topicId = UUID.randomUUID().toString();
            ForumTopic topic=new ForumTopic(topicId,userId,forumId,new Date(),0,content);
            forumTopicMapper.insert(topic);
            //创建图片关系
            if(imgs!=null&&imgs.length!=0) {
                for (String img : imgs) {
                    String imgId = UUID.randomUUID().toString();
                    ForumPhoto photo = new ForumPhoto(imgId, topicId, null, img);
                    forumPhotoMapper.insert(photo);
                }
            }
            //经验+15
            //用户是否关注
            ForumConcernExample concernExample1 = new ForumConcernExample();
            ForumConcernExample.Criteria criteria = concernExample1.createCriteria();
            criteria.andUserIdEqualTo(userId);
            criteria.andForumIdEqualTo(forumId);
            List<ForumConcern> forumConcerns = forumConcernMapper.selectByExample(concernExample1);
            if(forumConcerns.size()==1){
                //已关注，经验+15
                ForumExpExample expExample=new ForumExpExample();
                ForumExpExample.Criteria criteria1 = expExample.createCriteria();
                criteria1.andUserIdEqualTo(userId);
                criteria1.andForumIdEqualTo(forumId);
                //获取经验表
                ForumExp forumExp = forumExpMapper.selectByExample(expExample).get(0);
                //经验+15后保存
                forumExp.setExp(forumExp.getExp()+15);
                forumExpMapper.updateByPrimaryKey(forumExp);
                return "1";
            }
            return "2";
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
    }
    /*
    获取用户社区信息
     */
    @Override
    public CenterUser findUser(String userId) {
        CenterUser centerUser = centerUserMapper.selectByPrimaryKey(userId);
        return centerUser;
    }
    /*
    社区详情
     */
    @Override
    public Map<String, Object> findForumDetails(String userId, String forumId) {
        //查询社区信息
        ForumForum forumForum = frumForumMapper.selectByPrimaryKey(forumId);
        //社区用户
        long forumUserNum = forumRedis.findForumUserNum(forumId);
        //话题数量
        long forumTopicNum = forumRedis.findForumTopicNum(forumId);
        //社区管理员
        ForumAdminExample adminExample=new ForumAdminExample();
        adminExample.createCriteria().andForumIdEqualTo(forumId);
        List<ForumAdmin> forumAdminsIds = forumAdminMapper.selectByExample(adminExample);
        List<CenterUser>forumAdmins =new ArrayList<>();
        for(ForumAdmin forumAdmin : forumAdminsIds){
            CenterUser centerUser = centerUserMapper.selectByPrimaryKey(forumAdmin.getUserId());
            forumAdmins.add(centerUser);
        }
        //当前用户是否是管理员
        ForumAdminExample forumAdmin=new ForumAdminExample();
        ForumAdminExample.Criteria criteria = forumAdmin.createCriteria();
        criteria.andForumIdEqualTo(forumId);
        criteria.andUserIdEqualTo(userId);
        int status = forumAdminMapper.selectByExample(forumAdmin).size();
        //保存
        Map<String, Object> data=new HashMap<>();
        data.put("forumForum",forumForum);
        data.put("forumUserNum",forumUserNum);
        data.put("forumTopicNum",forumTopicNum);
        data.put("forumAdmins",forumAdmins);
        data.put("status",status);
        return data;
    }
    /*
    管理员申请
     */
    @Override
    public Integer addAdminService(String userId, String forumId, String content) {
        try {
            //当前用户是否是管理员
            ForumAdminExample forumAdmin=new ForumAdminExample();
            ForumAdminExample.Criteria criteria = forumAdmin.createCriteria();
            criteria.andForumIdEqualTo(forumId);
            criteria.andUserIdEqualTo(userId);
            int status = forumAdminMapper.selectByExample(forumAdmin).size();
            if(status==0){
                //创建申请
                String id = UUID.randomUUID().toString();
                ForumAdminApply adminApply=new ForumAdminApply(id,userId,forumId,new Date(),1,content);
                forumAdminApplyMapper.insert(adminApply);
            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    /*
    修改社区信息
     */
    @Override
    public Integer submitForumService(ForumForum forumForum) {
        try {
            Date date = frumForumMapper.selectByPrimaryKey(forumForum.getId()).getDate();
            forumForum.setDate(date);
            frumForumMapper.updateByPrimaryKey(forumForum);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    /*
    查询所有社区
     */
    @Override
    public List<ForumForum> allForumService() {
        ForumForumExample frumExample=new ForumForumExample();
        List<ForumForum> forumForums = frumForumMapper.selectByExample(frumExample);
        return forumForums;
    }

}
